package coml.allen.api.ack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * @author sesshomaru
 * @date 2020/11/14 18:25
 */
public class MyConsumer extends DefaultConsumer {

    private Channel channel;

    public MyConsumer(Channel channel){
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.err.println("------------ 自定义的 consumer ------------");
        System.err.println("consumerTag: " + consumerTag);
        System.err.println("envelope: " + envelope);
        System.err.println("properties: " + properties);
        System.err.println("body: " + new String(body));

        int num = (Integer) properties.getHeaders().get("num");
        if (num == 0) {
            /**
             * long deliveryTag,
             * boolean multiple,
             * boolean requeue  是否重回队列,会把这个消费失败的消息重新添加到 队列的尾部
             */
            channel.basicNack(envelope.getDeliveryTag(),false,true);
        } else {
            channel.basicAck(envelope.getDeliveryTag(), false);
        }
    }
}
